package com.lagou.client;

import com.lagou.service.RpcRequest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcConsumer {

    //创建线程池对象
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //1.创建一个代理对象 providerName：UserService#sayHello are you ok?
    public Object createProxy(final Class<?> serviceClass) {
        //借助JDK动态代理生成代理对象
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                //获取可用的服务端
                UserClientHandler userClientHandler = UserClientUtil.getAvailableUserClientHandler();
//                if (RpcConsumer.userClientHandler == null) {
//                    initClient();
//                }

                //封装
                RpcRequest request = new RpcRequest();
                String requestId = UUID.randomUUID().toString();
                String className = method.getDeclaringClass().getName();
                String methodName = method.getName();

                Class<?>[] parameterTypes = method.getParameterTypes();

                request.setRequestId(requestId);
                request.setClassName(className);
                request.setMethodName(methodName);
                request.setParameterTypes(parameterTypes);
                request.setParameters(args);


                // 设置参数
                userClientHandler.setPara(request);
                System.out.println(request);

                // 去服务端请求数据

                return executor.submit(userClientHandler).get();
            }
        });


    }
}
